package cn.hongwei.nacos.handler.namespace;

import cn.hongwei.nacos.annotation.Handler;
import cn.hongwei.nacos.constant.RequestConstants;
import cn.hongwei.nacos.context.InstanceContext;
import cn.hongwei.nacos.dto.NamespaceDto;
import cn.hongwei.nacos.handler.base.InstanceBaseHandler;
import cn.hongwei.nacos.param.NacosInfoParam;
import cn.hongwei.nacos.param.NacosServicesListParam;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author Great
 * @email 1224028994@qq.com
 * 处理名称空间的handler
 */
@Handler
public class NameSpaceHandler extends InstanceBaseHandler {

    @Override
    public void doHandler(InstanceContext instanceContext) {
        NacosInfoParam nacosInfoParam = instanceContext.getInstanceRequest().getNacosInfoParam();
        try {
            //uri /nacos/v1/console/namespaces
            Request request = new Request.Builder()
                    .get()
                    .url(RequestConstants.PROTOCOL_PREFIX +nacosInfoParam.getIp()+RequestConstants.MARK_COLON+nacosInfoParam.getPort()+RequestConstants.NAMESPACE_PATH)
                    .build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            String string = body.string();
            NamespaceDto namespaceDto = objectMapper.readValue(string, NamespaceDto.class);
            //给下一个请求设置请求参数
            NacosServicesListParam nacosServicesListParam = new NacosServicesListParam();
            nacosServicesListParam.setIp(nacosInfoParam.getIp());
            nacosServicesListParam.setPort(nacosInfoParam.getPort());
            nacosServicesListParam.setNamespaceDto(namespaceDto);
            instanceContext.getInstanceRequest().setNacosServicesListParam(nacosServicesListParam);
            //设置本次请求的响应参数
            instanceContext.getInstanceResponse().setNamespaceDto(namespaceDto);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

        doNextHandler(instanceContext);
    }
}
